import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'


const httpCodeMsg = {
    "404":"资源不存在",
    "500":"服务器运行异常"
}

const request = axios.create({
    baseURL: process.env.VUE_APP_AJAX_URL
})

request.interceptors.request.use(function(config){
    // console.log("请求拦截器-拦截的请求配置：",config)
    if(!config.isPublic){
        config.headers.Authorization = store.state.token
    }
    return config
},function(error){
    return Promise.reject(error)
})

request.interceptors.response.use(function (response) { 
    let result = response.data
    if(result.meta.status>=300){
        Message.error(result.meta.msg)
        return 'error'
    }else{
        // Message.success(result.meta.msg)
        return result.data; 
    }
}, function (error) { 
    if( !(error instanceof Error) ){
        Message.error( error )
    }else if(!error.request){
        Message.error("页面代码错误，请联系管理员")
    }else if(!error.response){
        Message.error("请求超时")
    }else if(error.response == error.request){
        Message.error("网络连接失败，请稍后重试")
    }else{
        Message.error( httpCodeMsg[ error.response.status ]||"运行错误" )
    }
});

export default request